# -*- coding: utf-8 -*-

from rest_framework.decorators import action
from core.viewset import CustomModelViewSet
from core.response import JsonResponse
from apps.sys.models import Menu
from apps.sys.router.serializers import *


class RouterViewSet(CustomModelViewSet):
    """
    菜单管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = Menu.objects.all()
    serializer_class = RouterSerializer

    @action(detail=False, methods=["GET"])
    def get_routers(self, request):
        """用于前端获取当前角色的路由"""
        user = request.user
        queryset = self.queryset.filter(parent=None)
        if not user.is_superuser:
            menuIds = user.roles.values_list("menu__id", flat=True)
            queryset = Menu.objects.filter(id__in=menuIds, parent=None, status=0)
        serializer = RouterSerializer(queryset, many=True, request=request)
        data = serializer.data
        return JsonResponse(data=data, total=len(data), msg="获取成功")
